﻿using LatteCoffee.coffeemodel;
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Security.Policy;
using System.Threading;
using static LatteCoffee.coffeemodel.CoffeeMassageModel;

namespace LatteCoffee.coffeemake
{
    public class CoffeeMakes
    {
        private static CoffeeMakes instance;
        private CoffeeMakes() { }

        public static CoffeeMakes Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CoffeeMakes();
                }
                return instance;
            }
        }
        public void fructoseAftericeAftercoffeeMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public void iceAftercoffeeMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public void fructoseAftercoffeeMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public void fructoseAftercoffeeAfterMilkMake()
        {
            try
            {

            }
            catch (Exception)
            {
                return;
            }
        }
        public bool InServiceMenuBol = false;
        public bool IsMakingBol()
        {
            try
            {
                var dd = BaseService.Instance.ServerGet("device/status");
                //  Console.WriteLine(dd);
                var json = JsonConvert.DeserializeObject<CoffeeMassage>(dd);//Ready
                if (json != null)
                {
                    if (json.activeErrors.ToString().Contains("603"))
                    {
                        Form1.containerCoffeeGroundsBol = false;
                    }
                    else
                    {
                        Form1.containerCoffeeGroundsBol = true;
                    }

                    if (json.status == "Ready")
                    {
                        if (InServiceMenuBol)
                        {
                            Thread.Sleep(3000);
                            InServiceMenuBol = false;
                        }
                        return true;
                    }
                    else if (json.status == "InServiceMenu")
                    {
                        InServiceMenuBol = true;
                    }
                    else
                        return false;
                }
                return false;
            }
            catch (Exception)
            {

                return false;
            }
        }
        public Bitmap rotateImage(Bitmap b, float angle)
        {
            try
            {
                //创建位图用于旋转图片
                Double tangle = angle * Math.PI / 180;
                Console.WriteLine(tangle);
                int r = (int)Math.Sqrt((b.Width * b.Width) + (b.Height * b.Height));
                int w = (int)(Math.Abs(b.Height * Math.Sin(tangle)) + Math.Abs(b.Width * Math.Cos(tangle)));
                int h = (int)(Math.Abs(b.Height * Math.Cos(tangle)) + Math.Abs(b.Width * Math.Sin(tangle)));
                Console.WriteLine(w);
                Console.WriteLine(h);
                Console.WriteLine(b.Width);
                Console.WriteLine(b.Height);
                Bitmap returnBitmap = new Bitmap(w, h);

                //初始化Graphics类
                Graphics g = Graphics.FromImage(returnBitmap);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                //移动坐标原点到图片中心
                g.TranslateTransform((float)w / 2, (float)h / 2);
                //顺时针旋转对应angle的角度
                g.RotateTransform(angle);
                //移动坐标原地到原来的位置
                g.TranslateTransform(-(float)w / 2, -(float)h / 2);
                g.Clear(Color.White);
                //构造图片
                g.DrawImage(b, new System.Drawing.Point((w - b.Width) / 2, (h - b.Height) / 2));

                g.Dispose();
                //返回位图
                return returnBitmap;
            }
            catch (Exception)
            {

                return null;
            }

        }
        public string ToBase64(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                return "data:image/jpeg;base64," + strbaser64;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        public void CoffeeMaking(string coffeeName, string img)
        {
            try
            {
                while (!Form1.isMaking) { Thread.Sleep(10); }
                switch (coffeeName)
                {
                    case "1000":
                    case "1001":
                    case "1102":
                    case "1103":
                    case "1104":
                    case "1106":
                        Form1.AllBol = false;
                        Form1.RobotBol = false;
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                break;
                            }
                        }
                        Thread.Sleep(100);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        if (coffeeName == "1000")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.americano);//接美式
                        else if (coffeeName == "1001")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.AustralianStyleWhite);//接澳白
                        else if (coffeeName == "1102")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.cappuccino);//接卡布
                        else if (coffeeName == "1103")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk3);//接牛奶
                        else if (coffeeName == "1104")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.latte);//接拿铁
                        else if (coffeeName == "1106")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotchocolate);//接热巧
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDY_Down);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDYNN_Down);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DY_Down);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JKF_UP);
                        Console.WriteLine("yes3");
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        Thread.Sleep(5000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        Form1.AllBol = false;
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFWC_UP);
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        Thread.Sleep(100);
                        break;
                    case "1002":
                    case "1003":
                    case "1105":
                    case "1107":
                        Form1.AllBol = false;
                        Form1.RobotBol = false;
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                break;
                            }
                        }
                        Thread.Sleep(100);
                        Form1.isPrinter = false;
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        //if (coffeeName == "1003")
                        //{
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDY_UP);
                        //    if (coffeeName == "1003")
                        //    {
                        //        Thread.Sleep(100);
                        //        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDYNN_UP);
                        //    }
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DY_UP);
                        //    Thread.Sleep(100);
                        //    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JKF_UP);
                        //    Thread.Sleep(100);
                        //    Form1.AllBol = true;
                        //    Thread.Sleep(1000);
                        //}
                        if (coffeeName == "1002")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.cappuccino);//接卡布
                        else if (coffeeName == "1003")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk3);//接热牛奶
                        else if (coffeeName == "1105")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.latte);//接拿铁
                        else if (coffeeName == "1107")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotchocolate);//接热巧
                                                                                                                     //if (coffeeName == "1002")
                                                                                                                     //{
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDY_UP);
                        if (coffeeName == "1003")
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFDYNN_UP);
                        }
                        else if (coffeeName == "1107")
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_SFQKL_UP);
                        }
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DY_UP);
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JKF_UP);
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        var imgname = "";
                        try
                        {

                            Console.WriteLine("打印 " + DateTime.Now.ToString());
                            var base64url = GetUrlToBase64(img);
                            Console.WriteLine("打印1" + DateTime.Now.ToString());
                            if (base64url != "")
                            {
                                var bmp = Base64StringToImage(base64url);
                                if (bmp != null)
                                {
                                    var bmp145 = rotateImage(bmp, -145);
                                    if (bmp145 != null)
                                    {
                                        imgname = ToBase64(bmp145);
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        //   }
                        Thread.Sleep(2000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        Form1.AllBol = false;
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFWC_UP);
                        Console.WriteLine("yes3");
                        Thread.Sleep(1000);
                        Form1.RobotBol = false;
                        Thread.Sleep(1000);
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DDYJ);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                break;
                            }
                        }
                        Form1.AllBol = true;
                        bool ispbol = true;
                        try
                        {
                            Form1.pSocketClient.pbol = false;
                            Form1.IsReviecePrinter = false;
                            if (Form1.pSocketClient.State != WebSocketState.Open)
                            {
                                Form1.pSocketClient.Close();
                                Form1.Pwebsocket();
                                Thread.Sleep(3000);
                            }
                            Form1.pSocketClient.Send(JsonConvert.SerializeObject(new PrinterSel { code = 1, tag = 1 }));
                            Thread.Sleep(500);
                            int sel = 0;
                            while (!Form1.IsReviecePrinter)
                            {
                                sel++;
                                Thread.Sleep(500);
                                if (sel == 20)
                                {
                                    if (Form1.pSocketClient.State != WebSocketState.Open)
                                    {
                                        Form1.pSocketClient.Close();
                                        Form1.Pwebsocket();
                                        Thread.Sleep(3000);
                                        Form1.pSocketClient.Send(JsonConvert.SerializeObject(new PrinterSel { code = 1, tag = 1 }));
                                        Thread.Sleep(500);
                                    }
                                }
                                if (sel == 40)
                                {
                                    ispbol = false;
                                    Form1.AllBol = false;
                                    Thread.Sleep(100);
                                    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYWC_UP);
                                    Thread.Sleep(100);
                                    Form1.AllBol = true;
                                    Form1.ErrorMsg = "";
                                    break;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                        if (ispbol)
                        {
                            if (Form1.isPrinter)
                            {
                                Form1.RobotBol = false;
                                Form1.ErrorMsg = "";
                                if (Form1.pSocketClient.State != WebSocketState.Open)
                                {
                                    Form1.pSocketClient.Close();
                                    Form1.Pwebsocket();
                                    Thread.Sleep(3000);
                                }
                                Form1.ErrorMsg = "dy";
                                int dyint = 0;
                                while (Form1.ErrorMsg == "dy")
                                {
                                    if (dyint < 5)
                                    {
                                        try
                                        {
                                            if (Form1.pSocketClient.State != WebSocketState.Open)
                                            {
                                                Form1.pSocketClient.Close();
                                                Form1.Pwebsocket();
                                                Thread.Sleep(2000);
                                            }
                                            //Console.WriteLine("打印 " + DateTime.Now.ToString());
                                            //var base64url = GetUrlToBase64(img);
                                            //Console.WriteLine("打印1" + DateTime.Now.ToString());
                                            //if (base64url != "")
                                            //{
                                            //    var bmp = Base64StringToImage(base64url);
                                            //    if (bmp != null)
                                            //    {
                                            //        var bmp145 = rotateImage(bmp, -145);
                                            //        if (bmp145 != null)
                                            //        {
                                            //    var imgname = ToBase64(bmp145);
                                            //if (imgname != "")
                                            //{
                                            Console.WriteLine(imgname);
                                            //string imgname = GetUrlToBase64(img);
                                            Console.WriteLine(imgname.Length);
                                            //var Printer_Set = new PrinterSel2 { code = 2, tag = 1, data = new PrinterData { size = 90, img = Form1.SetImg(Form1.DYHImg) } };
                                            //var Printer_Set = new PrinterSel2 { code = 2, tag = 1, data = new PrinterData { size = 80, img = Form1.SetImg(Form1.DYHImg) } };
                                            var Printer_Set = new PrinterSel2 { code = 2, tag = 1, data = new PrinterData { size = 80, img = imgname } };
                                            Form1.pSocketClient.Send(JsonConvert.SerializeObject(Printer_Set));
                                            // }
                                            //  }
                                            // }
                                            // }
                                        }
                                        catch (Exception)
                                        {
                                        }
                                        Thread.Sleep(5000);
                                        dyint++;
                                    }
                                    else
                                    {
                                        Form1.ErrorMsg = "over";
                                        Thread.Sleep(2000);
                                    }
                                }
                                try
                                {
                                    Form1.IsReviecePrinter = false;
                                }
                                catch (Exception)
                                {
                                }

                                Thread.Sleep(1000);
                                int imgindex = 0;
                                while (Form1.ErrorMsg != "over" && Form1.ErrorMsg != "ok1")
                                {
                                    Thread.Sleep(1000);
                                    imgindex++;
                                    if (imgindex == 27)
                                    {
                                        if (Form1.ErrorMsg == "")
                                        {
                                            Form1.pSocketClient.Close();
                                            Form1.ErrorMsg = "over";
                                            break;
                                        }
                                    }
                                    else if (imgindex == 180)
                                    {
                                        if (Form1.ErrorMsg == "top")
                                        {
                                            Form1.ErrorMsg = "over";
                                            break;
                                        }
                                    }
                                    else if (imgindex == 60)
                                    {
                                        if (Form1.ErrorMsg == "ok")
                                        {
                                            Form1.ErrorMsg = "over";
                                            break;
                                        }
                                    }
                                }
                                if (Form1.ErrorMsg == "over")
                                {
                                    Form1.AllBol = false;
                                    Thread.Sleep(100);
                                    ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYWC_UP);
                                    Thread.Sleep(100);
                                    Form1.AllBol = true;
                                    Form1.ErrorMsg = "";
                                }
                                try
                                {
                                    Form1.pSocketClient.pbol = true;
                                }
                                catch (Exception)
                                {
                                }

                                Form1.RobotBol = true;
                            }
                            else
                            {
                                Form1.AllBol = false;
                                Thread.Sleep(100);
                                ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYWC_UP);
                                Thread.Sleep(100);
                                Form1.AllBol = true;
                                Form1.ErrorMsg = "";
                            }
                        }
                        break;
                    case "1004":
                    case "1005":
                    case "1006":
                    case "1007":
                        Form1.AllBol = false;
                        Form1.RobotBol = false;
                        while (true)
                        {
                            Thread.Sleep(100);
                            ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                            Thread.Sleep(100);
                            if (Form1.RobotBol)
                            {
                                Thread.Sleep(100);
                                ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_UP);
                                Thread.Sleep(100);
                                break;
                            }
                        }
                        Form1.AllBol = true;
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        if (coffeeName == "1007")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.chocolate);//接qiaokeli
                        else
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.espresso);//接意式
                        RobotOperate.Robot_Move(4);
                        RobotOperate.Robot_Move(13);
                        Form1.AllBol = false;
                        Thread.Sleep(100);
                        ElseSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_Down);
                        Thread.Sleep(100);
                        Form1.AllBol = true;
                        Thread.Sleep(5000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        RobotOperate.Robot_Move(17);
                        RobotOperate.Robot_Move(9);
                        RobotOperate.Robot_Move(14);
                        if (coffeeName == "1004")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk);//接牛奶天鹅
                        else if (coffeeName == "1005")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk2);//接牛奶郁金香
                        else if (coffeeName == "1006")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk1);//接牛奶叶子
                        else if (coffeeName == "1007")
                            BaseService.Instance.HttpPost("control/dispense-product", CoffeeProductIDs.hotmilk4);//接牛奶巧克力
                        Thread.Sleep(5000);
                        while (!Form1.isMaking) { Thread.Sleep(10); }
                        if (coffeeName == "1004")
                            RobotOperate.Robot_Move(10);
                        else if (coffeeName == "1005")
                            RobotOperate.Robot_Move(21);
                        else if (coffeeName == "1006")
                            RobotOperate.Robot_Move(22);
                        else if (coffeeName == "1007")
                            RobotOperate.Robot_Move(23);
                        break;
                    default:
                        break;

                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="path">图片地址</param>
        /// <returns></returns>
        public static string SetImg(string path)
        {
            return "image/jpeg;base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(path));
        }
        /// <summary>
        /// 获取网络图片转换为base64
        /// </summary>
        /// <param name="url">网络图片路径   例：http://123.123.123.123/a.jpg</param>
        /// <returns></returns>
        public string GetUrlToBase64(string url)
        {
            try
            {
                var base64String = "";
                HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
                HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
                string base64sstr = string.Empty;
                using (Stream stream = webResponse.GetResponseStream())
                {
                    var mStream = new MemoryStream();

                    byte[] buffer = new byte[1024];
                    int byteCount;
                    do
                    {
                        byteCount = stream.Read(buffer, 0, buffer.Length);
                        mStream.Write(buffer, 0, byteCount);
                    } while (byteCount > 0);

                    mStream.Seek(0, SeekOrigin.Begin);
                    base64String = Convert.ToBase64String(mStream.ToArray());
                }
                //return base64String;
                WebClient mywebclient = new WebClient();
                byte[] Bytes = mywebclient.DownloadData(url);
                string Base64string = Convert.ToBase64String(Bytes);
                return base64String;
            }
            catch (Exception e)
            {
                return "";
            }
        }
        public Bitmap Base64StringToImage(string inputStr)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                return bmp;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return null;
            }
        }
        /// <summary>
        /// 制作拉花咖啡----天鹅
        /// </summary>
        /// <param name="makecoffee"></param>
        public void cooffeeAfterMilkMake(string makecoffee, string makemilk)
        {
            try
            {

                coffeemodel.RobotOperate.Robot_Move(1); //咖啡制作流程
                BaseService.Instance.HttpPost("control/dispense-product", makecoffee);//接意式
                while (!Form1.isMaking)
                {
                    Thread.Sleep(10);
                    //var dd = BaseService.Instance.ServerGet("device/status");
                    //var json = JsonConvert.DeserializeObject<CoffeeMassage>(dd);//Ready
                    //if (json.status == "Ready")
                    //    break;
                }
                BaseService.Instance.HttpPost("control/dispense-product", makemilk);//接牛奶
                Thread.Sleep(1000);
                while (true)
                {
                    Thread.Sleep(10);
                    var dd = BaseService.Instance.ServerGet("device/status");
                    var json = JsonConvert.DeserializeObject<CoffeeMassage>(dd);//Ready
                    if (json.status == "Ready")
                        break;
                }
                coffeemodel.RobotOperate.Robot_Initial_Point(); //通过关节直线到初始点
                coffeemodel.RobotOperate.Robot_servo_j();//读取关节角度进行运动202304
            }
            catch (Exception)
            {
                return;
            }
        }
    }
}
